<script lang="ts">
  import type { File } from "$lib/ebm";
  import { actixGraphqlEndpoint } from "$lib/js/stores";
  import { request, gql } from "graphql-request";

  import {
    useQuery,
    useMutation,
    useQueryClient,
  } from "@sveltestack/svelte-query";

  export let file: File;
  export let expanded = false;

  $: type = file.fileName.slice(file.fileName.lastIndexOf(".") + 1);

  function toggle() {
    expanded = !expanded;
  }

  const queryClient = useQueryClient();

  let endpoint = $actixGraphqlEndpoint;
  const openFileMutation = useMutation<
    File,
    { message: string },
    {
      file_id: string;
    }
  >(
    async ({ file_id }) => {
      const { file } = await request(
        endpoint,
        gql`
          mutation ($id: ID!) {
            file: openFile(input: { id: $id }) {
              id
              snapshotAt
              fileName
              fileMode
              fileOwner
              fileGroup
              fileSize
              title
              description
              content
              createdAt
              updatedAt
              status
              folderId
              from
            }
          }
        `,
        {
          id: file_id,
        }
      );
      return file;
    },
    {
      onSuccess: () => {
        queryClient.invalidateQueries("filesopened");
      },
    }
  );

  function openFile() {
    $openFileMutation.mutate({
      file_id: file.id,
    });
    console.log("double click to open file={}, id={}", file.fileName, file.id);
  }
</script>

<span
  class="hover:bg-rose-200 truncate w-full"
  style="background-image: url(icons/{type}.svg)"
  on:click={toggle}
  on:dblclick={openFile}>{file.fileName}</span
>

<style>
  span {
    padding: 0 0 0 1.5em;
    background: 0 0.1em no-repeat;
    background-size: 1em 1em;
    cursor: pointer;
  }
</style>
